<template lang="">
  <div class="edit-password">
    <h3 >{{ $t('bian-2') }}</h3>
    <div style="max-width: 50%">
      <a-form
        :model="formState"
        name="validate_other"
        v-bind="formItemLayout"
        ref="formRef"
      >
        <a-form-item name="upload" :label="$t('touX')" extra="">
          <div @click="selectUserAvatar">
            <img v-if="formState.avatar" :src="formState.avatar" alt="avatar" />
            <div v-else>
              <div class="ant-upload ant-upload-select ant-upload-select-picture-card">
                <span tabindex="0" class="ant-upload" role="button">
                  <div>
                    <span role="img" aria-label="plus" class="anticon anticon-plus">
                      <svg focusable="false" class="" data-icon="plus" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><defs></defs><path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path><path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path></svg>
                    </span>
                    <div class="ant-upload-text">{{ $t('shang-0') }}</div>
                  </div>
                </span>
              </div>
            </div>
          </div>
        </a-form-item>
        
        <a-form-item
          name="member_level"
          :label="$t('huiY-2')"
        >
          <a-input size="large" :disabled="true" v-model:value="formState.member_level" />
        </a-form-item>

        <a-form-item
          name="real_name"
          :label="$t('zhen-2')"
          :rules="[{ required: true, message: '请输入真实姓名' }]"
        >
          <a-input  size="large" v-model:value="formState.real_name" :placeholder="$t('qing-12')" />
          <p style="margin: 0;font-size: 12px">
            <span class="text-tip">{{ $t('tiKu') }}</span>
          </p>
        </a-form-item>

        <a-form-item
          name="gender"
          :label="$t('xing')"
          :rules="[{ required: true, message: '请选择性别' }]"
        >
          <a-select  size="large" v-model:value="formState.gender" :placeholder="$t('qing-13')">
            <a-select-option :value="2">{{ $t('nan') }}</a-select-option>
            <a-select-option :value="3">{{ $t('nv') }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item 
          name="birthday" 
          :label="$t('chuS')" 
          :rules="[{ type: 'string' as const, required: true, message: '请选择日期' }]">
          <a-date-picker 
            size="large"
            v-model:value="formState['birthday']" 
            value-format="YYYY-MM-DD" 
            :placeholder="$t('qing-14')" 
            format="YYYY-MM-DD"
          />
        </a-form-item>

        <a-form-item
          name="phone_number"
          :label="$t('shou-2')"
          :rules="[{ 
            required: true, message: '请输入11位有效手机号码',
            max: 11, message: '请输入11位有效手机号码'
          }]"
        >
          <a-input-group compact style="display: flex">
            <a-select v-model:value="mobilePhoneArea" size="large" style="width: 80px">
              <a-select-option 
                v-for="(value, index) in countryCodes" 
                :value="value" 
                :key="'mobilePhoneArea' + index"
              >{{ value }}</a-select-option>
            </a-select>
            <a-input v-model:value="formState.phone_number" :placeholder="$t('qing-11')" size="large" />
          </a-input-group>
        </a-form-item>


        <a-form-item
          name="verify_code"
          :label="$t('yanZ')"
          :rules="[{ 
            required: true, message: '请输入验证码',
            max: 5, message: '请输入5位有效验证码'
          }]"
        >
          <a-input v-model:value="formState.verify_code" :placeholder="$t('qing-3')" size="large">
            <template #addonAfter>
              <a-button size="large" :loading="sending" @click="handleSendSmsCode">{{ buttonText }}</a-button>
            </template>
          </a-input>
        </a-form-item>
      </a-form>

      <a-button type="primary" size="large"  danger block style="margin-top: 10px" @click="onSubmit">{{ $t('baoC') }}</a-button>
    </div>
    <UserAvatarModal 
      :visible="modalVisible" 
      @ok="handleOk" 
      @cancel="handleCancel"
    />
  </div>

</template>
<script setup lang="ts">
import { ref, defineProps, defineEmits, reactive, onBeforeMount, toRaw, onMounted } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import type { FormInstance } from 'ant-design-vue';
import { countryCodes, generateMd5, getBase64, getMobilePhoneInfo } from '@/utils';
import { setWithdrawalsPassword } from '@/api/safety';
import { message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import type { UploadFile } from 'ant-design-vue/es/upload/interface';
import { sendSMSCode, updateUserInfo } from '@/api/account';
import { useUserStore } from '@/stores/userInfo';
import UserAvatarModal from "./components/UserAvatarModal.vue";
import { Form } from 'ant-design-vue';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const useForm = Form.useForm;

const userStore = useUserStore();
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};

const countdownSecond = 90;
const sending = ref<boolean>(false);
const buttonText = ref<string>(t('faSo-0'));
const countDown = ref<number>(countdownSecond);
const hasDisabledSent = ref<boolean>(false);
const formRef = ref<FormInstance>();

const fileList = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');

const curPhoneNumber = computed(() => {
  const { phoneNumber } = getMobilePhoneInfo(userStore.user.phone_number || '');
  return phoneNumber || '';
})
const mobilePhoneArea = computed(() => {
  const { areaCode } = getMobilePhoneInfo(userStore.user.phone_number || '');
  return areaCode || '+86';
});

const member_level = computed(() => userStore.user.member_level || '');
const real_name = computed(() => {
  let value = userStore.user.real_name || ''
  return value;
});
const gender = computed(() => userStore.user.gender || '');
const birthday = computed(() => userStore.user.birthday || '');
const avatar = computed(() => userStore.user.avatar || '');

function createUserInfo() {
  return Object.assign({}, {
    "member_level": member_level,
    "real_name": '',
    "gender": null,
    "birthday": '',
    "phone_number": '',
    "verify_code": "",
    "avatar": ''
  })
}

const formState = reactive<Record<string, any>>(createUserInfo());
// const [ form ] = useForm(formState);

const subscribe = userStore.$subscribe(
  (mutation: any, state: any) => {
    /*
      * mutation主要包含三个属性值：
      *   events：当前state改变的具体数据，包括改变前的值和改变后的值等等数据
      *   storeId：是当前store的id
      *   type：用于记录这次数据变化是通过什么途径，主要有三个分别是
*         “direct” ：通过 action 变化的
          ”patch object“ ：通过 $patch 传递对象的方式改变的
          “patch function” ：通过 $patch 传递函数的方式改变的
      *
      * */
    console.log(mutation);
    // 在此处监听store中值的变化，当变化为某个值的时候，做一些业务操作
    const user = state.user;
    if (user) {
      formState.real_name = user.real_name;
      formState.gender = user.gender;
      formState.birthday = user.birthday;

      if (user.phone_number) {
        const { phoneNumber } = getMobilePhoneInfo(user.phone_number);
        formState.phone_number = phoneNumber;
      }
      formState.avatar = user.avatar;
    }
  },
  { detached: false }
  // detached:布尔值，默认是 false，正常情况下，当订阅所在的组件被卸载时，订阅将被停止删除，
  // 如果设置detached值为 true 时，即使所在组件被卸载，订阅依然在生效
  // 参考文档：https://pinia.web3doc.top/core-concepts/state.html#%E8%AE%A2%E9%98%85%E7%8A%B6%E6%80%81
)
let timer: any = null;
const handleSendSmsCode = () => {
  if (!formState.phone_number) {
    // 手机号为空，提示用户
    message.warn('手机号码不能为空!');
    return
  }
  
  if (hasDisabledSent.value) {
    return;
  }

  // 请求验证码
  sending.value = true
  sendSMSCode({phone_number: mobilePhoneArea.value + formState.phone_number })
  .then(() => {
    buttonText.value = `${countDown.value} 秒后重新发送`
    timer= setInterval(() => {
      countDown.value = countDown.value - 1
      buttonText.value = `${countDown.value} 秒后重新发送`

      if (countDown.value <= 0) {
        clearInterval(timer)
        hasDisabledSent.value = false
        buttonText.value = '发送验证码'
        countDown.value = countdownSecond;
      }
    }, 1000)
  }).catch((e: any) => {
    console.log(e);
    clearInterval(timer);
  }).finally(() => {
    sending.value = false
    hasDisabledSent.value = true;
  })
}
const onSubmit = () => {
  if (!formRef.value) return;

  formRef.value
    .validate()
    .then(() => {
      console.log('submit!', toRaw(formState));
      fetchUpdateUserInfo();
    })
    .catch(error => {
      console.log('error', error);
    });
};
const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
};

const fetchUpdateUserInfo = () => {
  updateUserInfo({
    "real_name": formState.real_name,
    "gender": formState.gender,
    "birthday": formState.birthday,
    "phone_number": mobilePhoneArea.value + formState.phone_number,
    "verify_code": formState.verify_code,
    "avatar": formState.avatar
  })
    .then((data: any) => {
      if (data.status === "OK") {
        message.success(t('xiuG-0'));
        userStore.updateUserInfo();
      }
    })
}

const modalVisible = ref<boolean>(false);
function selectUserAvatar() {
  modalVisible.value = true;
}
function handleOk(selectedAvatars: string) {
  formState.avatar = selectedAvatars;
  // 在这里执行提交操作
  modalVisible.value = false;
}
function handleCancel() {
  modalVisible.value = false;
}

</script>
<style lang="less">
.edit-password {
  .ant-input-group-addon {
    padding: 0;
    background-color: transparent;
    border: none;
  }
}
</style>